// Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
// This source file is part of the Cangjie project, licensed under Apache-2.0
// with Runtime Library Exception.
//
// See https://cangjie-lang.cn/pages/LICENSE for license information.

#ifndef CANGJIE_MIGRATOR_CANGJIETOOLS_COMPILER
#define CANGJIE_MIGRATOR_CANGJIETOOLS_COMPILER

#include "cangjie/Frontend/CompilerInstance.h"
#include "cangjie/AST/Walker.h"

#include "Platform/TempDirectory.h"

#include "Path.h"
#include "UpdateInstance.h"
#include "Rules/RuleList.h"

namespace CangjieMigrator::CangjieTools {

using AstRootNode = Ptr<Cangjie::AST::File>;
using TraverseFunc = std::function<Cangjie::AST::VisitAction(const Cangjie::AST::Node &)>;

class Compiler {
public:
    explicit Compiler(Path cangjieHome);

    [[nodiscard]] Path GetOutputPath() const;

    void CompileSema(const std::vector<Path> &inputs, const std::vector<Path> &imports, bool isCompilePackage);
    void CompileSemaFile(const std::vector<Path> &files, const std::vector<Path> &imports);
    void CompileSemaPackage(const UpdateInstance::Package &package);
    void CompileSemaPackage(const std::vector<Path> &packages, const std::vector<Path> &imports);

    [[nodiscard]] AstRootNode GetAstRootNode() const;
    [[nodiscard]] std::vector<AstRootNode> GetAstRootNodes() const;

    static void TraverseAst(AstRootNode rootNode, const TraverseFunc &func);
    static void TraverseAst(AstRootNode rootNode, const std::unique_ptr<Rules::RuleList> &rules, UpdateInstance::File &file);

private:
    Platform::TempDirectory tempDirectory;
    Path cangjieHome;
    std::unique_ptr<Cangjie::CompilerInstance> instance;

    void RemoveMacroInList() const;
    void Compile() const;
};

}  // namespace CangjieMigrator::CangjieTools

#endif  // CANGJIE_MIGRATOR_CANGJIETOOLS_COMPILER
